<?php

namespace app\common\services;


use app\admin\model\yalimedia\course\Content;
use app\admin\model\yalimedia\course\Contentlog;
use app\admin\model\yalimedia\course\Unit;
use app\admin\model\yalimedia\Fav;
use app\admin\model\yalimedia\Uservip;
use app\admin\model\YalimediaCourseUser;
use app\common\model\CourseQuestion as CourseQuestionModel;
use app\common\model\courseContentLog as courseContentLogModel;
use app\common\model\CourseQuestionCategory as CourseQuestionCategoryModel;
use app\common\model\Config as ConfigModel;

use app\common\model\YalimediaQuestionLog as YalimediaQuestionLogModel;

use app\common\model\Course as CoursekModel;
use app\common\services\UrlService;
use think\facade\Db;

use think\facade\Cache;

use tree\tree;

class CourseService
{

    public $model;
    public $error;

    public function __construct()
    {
        $this->model = new \app\admin\model\yalimedia\Course();
    }

    public function courseIsPay($course_id,$user_id)
    {
        $isbuy = $this->model->where('id',$course_id)->value('is_buy');
        if($isbuy){
            $data = YalimediaCourseUser::where(['user_id'=>$user_id,'course_id'=>$course_id])->find();
            if($data){
                return 1;
            }else{
                return 0;
            }
        }
        return 1;
    }

    public function getMyCourseList($user_id,$where,$page,$limit)
    {
        $count = $this->model->alias('a')->join('yalimedia_course_user b','a.id=b.course_id')->where(function($query) use($where,$user_id){$query->where(array_merge($where,['status'=>1,'user_id'=>$user_id]));})->whereOr(function($query){$query->where(['is_buy'=>0,'status'=>1]);})->group('a.id')->count();

        $field = 'a.id,a.title,a.cover,a.is_buy';
        if($page){
            $data = $this->model->alias('a')->join('yalimedia_course_user b','a.id=b.course_id')->where(function($query) use($where,$user_id){$query->where(array_merge($where,['status'=>1,'user_id'=>$user_id]));})->whereOr(function($query){$query->where(['is_buy'=>0,'status'=>1]);})->group('a.id')->page($page,$limit)->order("weigh asc")->field($field)->select();
        }else{
            $data = $this->model->alias('a')->join('yalimedia_course_user b','a.id=b.course_id')->where(function($query) use($where,$user_id){$query->where(array_merge($where,['status'=>1,'user_id'=>$user_id]));})->whereOr(function($query){$query->where(['is_buy'=>0,'status'=>1]);})->group('a.id')->field($field)->select();
        }
        return ['total'=>$count,'data'=>$data];
    }
    /**
     * 获取课程列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getCourseList($user_id,$where,$page,$limit){

        $count = $this->model->where($where)->where(['status'=>1])->count();
        $field = 'id,title,cover,is_buy';
        if($page){
            $data = $this->model->where($where)->where(['status'=>1])->page($page,$limit)->order("weigh asc")->field($field)->select();
        }else{
            $data = $this->model->where($where)->where(['status'=>1])->order("weigh asc")->field($field)->select();
        }
        foreach ($data as &$v){
            $v['is_pay'] = $this->courseIsPay($v['id'],$user_id);
        }
        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取热门课程列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getHotCourseList($page,$limit){

        $where = ['is_hot'=>1,'status'=>1];
        $count = $this->model->where($where)->count();
        if($page){
            $data = $this->model->where($where)->page($page,$limit)->order("weigh asc")->select();
        }else{
            $data = $this->model->where($where)->order("weigh asc")->select();
        }

        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取课程详情
     */
    public function getCourseInfo($id,$user_id){

        // 判断当前用户的类型
        $courseModel = new \app\admin\model\yalimedia\Course();
        // $courseInfo = $courseModel->where(['cate_id'=>$id,'status'=>1])->field("id,title,cover,content")->find();
        $courseInfo = $courseModel->where(['id'=>$id,'status'=>1])->find();
        if(empty($courseInfo)){
            $this->error = "当前课程不存在";
            return false;
        }
        $courseInfo['is_pay'] = (new CourseService())->courseIsPay($id,$user_id);
        $id = $courseInfo['id'];
        
        // //完善接口连接
        // $courseInfo['cover']    = request()->domain().$courseInfo['cover'];
        $courseInfo['cover']    = urlService::getFileUrl($courseInfo['cover']);
        
        $courseInfo['content']  = preg_replace('#src="/#is', 'src="'.request()->domain().'/',$courseInfo['content']);

        // //完善教师信息
        // $teacherModel = new \app\admin\model\yalimedia\Teacher();
        // $teacherInfo = $teacherModel->where(['id'=>$courseInfo['teacher_id']])->find();
        // if(!empty($teacherInfo)){
        //     $teacherInfo['image'] = request()->domain()."/".$teacherInfo['image'];
        //     $teacher = new Teacher();
        //     $teacherInfo['course_num'] = $teacher->getCourseNum($courseInfo['teacher_id']);
        //     $teacherInfo['study_num'] = $teacher->getStudyNum($courseInfo['teacher_id']);
        // }
        // $courseInfo['teacher'] = $teacherInfo;
        
        //计算课时
        $courseUnitModel = new Unit();
        $unitList = collection($courseUnitModel->where(['course_id'=>$id])->order("weigh asc")->select())->toArray();
   
        $courseContentModel = new Content();
        $courseContentList  = collection($courseContentModel
            ->alias("content")
            // ->field("content.id,content.course_id,content.unit_id,content.title,content.type,content.media_title,content.media_id,content.media_cover,content.duration,IFNULL(log.id,0) as study_status")
            ->field("content.is_moni,content.id,content.unit_id,content.title,content.type,IFNULL(log.id,0) as study_status")
            ->join('yalimedia_course_content_log log',"content.id=log.content_id and log.user_id=".$user_id,'left')
            ->where(['content.course_id'=>$id])
            ->order("content.weigh asc")
            ->select())->toArray();
            
        $contentLogModel = new Contentlog();
        if($lastContent = $contentLogModel->where(['course_id'=>$id,'user_id'=>$user_id])->order("last_time desc")->find()){
            $last_content_id = $lastContent['content_id'];
        }else{
            $last_content_id = "";
        }
        
        $course_num = 0 ;
        foreach($unitList as &$v){
            $course = [];
            foreach($courseContentList as &$vv){
                
                $num      = 0;
                $done_num = 0;
                $last = "";
                if(!empty($vv['study_status'])){
                    $vv['study_status'] = 1;
                }else{
                    $vv['study_status'] = 0;
                }
                
                //判断是否为最后播放的节
                if($vv['id'] == $last_content_id && $last_content_id){
                    $vv['is_last']  = 1;
                }else{
                    $vv['is_last']  = 0;
                }
                
                $cate_list = CourseQuestionCategoryModel::where(['content_id' => ($vv['id']+9000)])->select();
                
                if(!empty($cate_list)){
               
                    foreach($cate_list as $k => $vvv){
                        
                        // 试题数量
                        $vvv['num']      = CourseQuestionModel::where('cate_id',$vvv['id'])->count();
                        // $vvv['done_num'] = courseContentLogModel::where(['course_id' => $vvv['id'],'user_id'=>$user_id ])->count();
                        $question_log    = YalimediaQuestionLogModel::where(['course_id' => $vvv['id'],'user_id'=>$user_id,'status'=>1 ])->field('last,right_count,error_count')->find();
                        $right_count     = $question_log['right_count'] ?? 0;
                        $error_count     = $question_log['error_count'] ?? 0;
                        $vvv['done_num'] = bcadd($right_count,$error_count);
                        $num      += $vvv['num'];
                        $done_num += $vvv['done_num'];
                        $last = $question_log['last']??"";
                    }
              
                }

                 #   树状图返回
                $tree       = new Tree();
                $tree->load(collection($cate_list)->toArray());
                $cate_list  = $tree->DeepTree() ?? [];

                $vv['list']      = $cate_list ?? [];
                $vv['num']       = $num;
                $vv['done_num']  = $done_num;
                $vv['last']  = $last;
                //组合章节
                if($vv['unit_id'] == $v['id']){
                    $course[] = $vv;
                }
            }
            $v['cover']     = urlService::getFileUrl($v['cover']);
            $v['course']    = $course;
            $course_num    += count($course);
        }
        
        $courseInfo['unit'] = $unitList;
        $courseInfo['course_count'] = $course_num;

        /**
         * 是否购买
         */
        $order = new \app\admin\model\yalimedia\Order();
        if($order->where(['type'=>1,'status'=>2,'item_id'=>$id,'user_id'=>$user_id])->find()){
            $courseInfo['is_buy'] = 1;
        }else{
            $courseInfo['is_buy'] = 0;
        }

        //获取学习人数
        $contentLogModel = new Contentlog();
        $courseInfo['study_count'] = $contentLogModel
            ->alias("log")
            ->join("yalimedia_course course","log.course_id=course.id")
            ->where(['log.course_id'=>$id,'course.status'=>1])
            ->group("log.user_id")
            ->count();

        return $courseInfo;
    }

    /**
     * 获取学习记录列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getContentLogList($user_id,$page,$limit){

        $contentLogModel = new Contentlog();
        $count = $contentLogModel
            ->alias("log")
            ->join("yalimedia_course course","log.course_id=course.id")
            ->where(['log.user_id'=>$user_id,'course.status'=>1])
            ->group("log.course_id")
            ->count();

        if($page){
            $data = $contentLogModel
                ->alias("log")
                ->field("course.*")
                ->join("yalimedia_course course","log.course_id=course.id")
                ->where(['log.user_id'=>$user_id,'course.status'=>1])
                ->group("log.course_id")
                ->page($page,$limit)->order("log.last_time desc")->select();
        }else{
            $data = $contentLogModel
                ->alias("log")
                ->field("course.*")
                ->join("yalimedia_course course","log.course_id=course.id")
                ->where(['log.user_id'=>$user_id,'course.status'=>1])
                ->group("log.course_id")
                ->order("log.last_time desc")->select();
        }

        return ['total'=>$count,'data'=>$data];
    }


    /**
     * 获取首页模块对应ID
     *
     * @return void
     */
    public static function getIndex(){

        $configModel = new ConfigModel;
        $result      = $configModel->where('name','IN',['word_id','call_id','read_id','hearing_id'])->column('value','name');
        if(empty($result)){
            return [];
        }
        return $result;
    }

    /**
     * 获取课程列表
     * @param $user_id
     * @return array|bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getHotList($user_id)
    {
      
        $list = CoursekModel::where(['status'=>1,'is_hot'=>1])->order("weigh asc")->field('id,title,cover,is_buy')->limit(3)->select() ?? [];
        foreach ($list as &$v){
            $v['is_pay'] = (new CourseService())->courseIsPay($v['id'],$user_id);
            $v['cover'] = urlService::getFileUrl($v['cover']);
        }
        return $list;
    }


}